package com.tz.crm.dao.impl;

import com.tz.crm.dao.PropertyDao;
import com.tz.crm.entity.Property;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 使用 @Repository 将 DAO 类声明为 Bean
 */
@Repository
@Transactional
public class PropertyDaoImpl extends BaseDaoImpl<Property, String>
        implements PropertyDao {

    @SuppressWarnings("unchecked")
    @Override
    public List<Property> getByContractTemplateId(String id) {
        String hql = "select p from Property p left join fetch p.contractTemplate where" +
                " p.contractTemplate.id=:id order by p.seq";
        Query query = getSession().createQuery(hql).setParameter("id", id);
        List<Property> propertyList = query.list();
        return propertyList;
    }

    @Override
    public int getPropertyAmount(String id) {
        String hql = "select count(p.id) from Property p where p.contractTemplate.id = :id";
        Query query = getSession().createQuery(hql);
        query.setParameter("id", id);
        return Integer.parseInt(query.uniqueResult() + "");
    }

    @Override
    public String save(Property property) {
        String id = property.getContractTemplate().getId();
        property.setSeq(getPropertyAmount(id));
        return super.save(property);
    }

    @Override
    public Property getPropertyBySeq(String templateId, int seq) {
        //todo:performance
        for (Property p : getByContractTemplateId(templateId)) {
            if (p.getSeq() == seq) {
                return p;
            }
        }
        return null;
    }

}
